package com.ruoyi.async;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CompletableFutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new CompletableFutureExample().supply();
//        new CompletableFutureExample().supply1();
//        new CompletableFutureExample().calculateAsync();
//        CompletableFuture.runAsync();

    }

    public void calculateAsync() throws InterruptedException {
        CompletableFuture<String> completableFuture
                = CompletableFuture.supplyAsync(() -> "Hello");

        CompletableFuture<Void> future = completableFuture
                .thenRun(() -> System.out.println("Computation finished."));
        try {
            future.get();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void supply() {
        // 创建一个异步任务
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作
            try {
                System.out.println("异步开始");
                Thread.sleep(2000); // 等待2秒
                System.out.println("异步结束");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Result of the asynchronous computation";
        });

        // 在异步任务完成后执行的操作
        future.thenAccept(result -> {
            System.out.println("异步任务完成，结果为: " + result);
        });

        // 主线程继续执行其他任务
        System.out.println("主线程继续执行其他任务...");

        while (!future.isDone()) {
            // 主线程可以在这里执行其他任务或等待
        }
//        System.out.println("异步任务完成，结果为: " + future.get());
    }

    private void supply1() {
        try {
            CompletableFuture<String> future
                    = CompletableFuture.supplyAsync(() -> "Hello");
            Thread.sleep(1000);
            System.out.println(future.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
